package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.client.service.ColumnServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.Column;
import com.hxkj.domain.po.WebsiteAddr;
import com.platform.common.domain.result.ResultDataStruct;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.*;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_COLUMN_ARTICLE;

/**
 * @ClassName ColumnsArticleDirective 多个分类文章列表集合标签解析
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/9/5 15:26
 * @Version 1.0
 */
@Component
@Log4j
public class ColumnsArticleDirective extends AbstractDirective {

    @Autowired
    private ColumnServiceClient columnServiceClient;

    @Autowired
    private ArticleServiceClient articleServiceClient;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 输入参数，分类ID字符串
     */
    public static final String COLUMN_IDS = "columnIds";
    /**
     * 输入参数，分类ID
     */
    public static final String COLUMN_ID = "columnId";
    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";
    /**
     * 输入参数，是否排序,0：升序，1：降序
     */
    public static final String SORT = "sort";
    /**
     * 输入参数，获取起始条数
     */
    public static final String START = "start";
    /**
     * 输入参数，排序的字段，多个用","隔开
     */
    public static final String LOCATION_LEVEL = "locationLevel";

    /**
     * 输入参数，获取置顶条数条数
     */
    public static final String IS_STICK_COUNT = "isStickCount";

    /**
     * 输入参数，获取条数
     */
    public static final String COUNT = "count";
    /**
     * 输入参数，是只查有图片的文章 0、为需要显示图片 1、为不需要显示图片
     */
    public static final String SHOW_IMG = "showImg";

    /**
     * 当前分类的文章列表
     */
    public static final String COLUMN_ARTICLE_LIST = "columnList";
    /**
     * 当前推荐图片文章列表
     */
    public static final String ARTICLE_LIST = "pushArticleList";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        env.getOut();
        try {
            //Mr.zheng:获取参数
            String columnIds = super.getString(COLUMN_IDS, params) == null ? "" : super.getString(COLUMN_IDS, params);
            //Mr.zheng:获取参数
            Long columnId = super.getLong(COLUMN_ID, params) == null ? (Long) getCustomAttrbute(env, COLUMN_ID) : super.getLong(COLUMN_ID, params);
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            //Mr.zheng:默认根据降序排序
            String sort = super.getString(SORT, params) == null ? "update_time DESC" : super.getString(SORT, params);
            //Mr.zheng:默认取5条文章
            int start = super.getInt(START, params) == null ? 1 : super.getInt(START, params);
            //Mr.zheng:默认取3条置顶文章
            int isStickCount = super.getInt(IS_STICK_COUNT, params) == null ? 0 : super.getInt(IS_STICK_COUNT, params);
            //Mr.zheng:默认取5条文章
            int count = super.getInt(COUNT, params) == null ? 5 : super.getInt(COUNT, params);
            //Mr.zheng:默认文章推荐等级不设置则为-1
            int locationLevel = super.getInt(LOCATION_LEVEL, params) == null ? -1 : super.getInt(LOCATION_LEVEL, params);
            //Mr.zheng:默认为0、需要带图片
            int showImg = super.getInt(SHOW_IMG, params) == null ? 0 : super.getInt(SHOW_IMG, params);
            String note = super.getNote(env);
            if (StringUtils.isEmpty(columnIds) && columnId == null) {
                log.warn("分类ID为空并且分类ID字符串也为空");
            }
            Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
            Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
            List<Article> articleList =  (List<Article>) redisTemplate.boundValueOps("directive_" + siteId + CMS_COLUMN_ARTICLE + "_" + columnIds + "_" + count + "_" + locationLevel + "_" + showImg + "_articleList").get();
            List<Column> columnList =  (List<Column>) redisTemplate.boundValueOps("directive_" + siteId + CMS_COLUMN_ARTICLE + "_" + columnIds + "_" + count + "_" + locationLevel + "_" + showImg + "_columnList").get();
            if (null != articleList && articleList.size() > 0 && null != columnList && columnList.size() > 0) {
                if (StringUtils.isBlank(note)) {
                    // 静态文件文章链接加前缀
                    for (Article item : articleList) {
                        String urlContext = siteCtxMap.get(item.getSiteId());
                        if(StringUtils.isNotBlank(urlContext)) {
                            item.setManuscriptPath(urlContext + item.getManuscriptPath());
                        }
                    }
                    // 静态文件分类链接加前缀
                    for (Column item : columnList) {
                        String urlContext = siteCtxMap.get(item.getSiteId());
                        if(StringUtils.isNotBlank(urlContext)) {
                            item.setManuscriptPath(urlContext + item.getManuscriptPath());
                        }
                    }
                }
                env.setVariable(ARTICLE_LIST, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(articleList));
                env.setVariable(COLUMN_ARTICLE_LIST, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(columnList));
            } else {

                Column column = new Column();
                column.setColumnIds(columnIds);
                if (StringUtils.isEmpty(columnIds)) {
                    column.setColumnId(columnId);
                }
                column.setSiteId(siteId);
                ResultDataStruct<List<Column>> resultDataStruct = columnServiceClient.getColumnList(column);
                columnList = resultDataStruct.getData();

                WebsiteAddr websiteAddr = getWebSiteAddr(siteId);
                for (Column col : columnList) {
                    Article article = new Article();

                    article.setSiteId(col.getSiteId());
                    article.setColumnId(col.getColumnId());
                    article.setSort(sort);
                    article.setStart(start - 1);
                    article.setCount(count);
                    article.setShowImg(showImg);
                    List<Article> articleList_ = new ArrayList<>();
                    String articleIds = "";

                    articleList_ = getColumnASArticleList(isStickCount, count, article, articleList_, articleIds);

                    if (StringUtils.isNotBlank(note)) {
                        col.setManuscriptPath(websiteAddr.getIpAdd() + col.getManuscriptPath());
                        for (Article artic : articleList_) {
                            artic.setManuscriptPath(websiteAddr.getIpAdd() + article.getManuscriptPath());
                        }
                    }else {
                        // 静态文件分类及下级文章链接加前缀
                        String urlContext = siteCtxMap.get(col.getSiteId());
                        if(StringUtils.isNotBlank(urlContext)) {
                            col.setManuscriptPath(urlContext + col.getManuscriptPath());
                            for (Article item : articleList_) {
                                item.setManuscriptPath(urlContext + item.getManuscriptPath());
                            }
                        }
                    }
                    col.setArticleList(articleList_);//封装该分类的文章列表
                }
                env.setVariable(COLUMN_ARTICLE_LIST, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(columnList));
                redisTemplate.boundValueOps("directive_" + siteId + CMS_COLUMN_ARTICLE + "_columnList").set(columnList);

                //Mr.zheng:封装推荐位文章
                if (locationLevel > 0) {
                    Article article = new Article();
                    article.setLocationLevel(locationLevel);
                    article.setSiteId(siteId);
                    article.setSort(sort);
                    article.setStart(start - 1);
                    article.setCount(count);
                    article.setShowImg(showImg);
                    article.setColumnIds(columnIds);
                    article.setColumnId(columnId);
                    articleList = articleServiceClient.getArticleListByParam(article);
                    if (StringUtils.isNotBlank(note)) {
                        for (Article art : articleList) {
                            art.setManuscriptPath(websiteAddr.getIpAdd() + art.getManuscriptPath());
                        }
                    }else {
                        // 静态文件文章链接加前缀
                        for (Article item : articleList) {
                            String urlContext = siteCtxMap.get(item.getSiteId());
                            if(StringUtils.isNotBlank(urlContext)) {
                                item.setManuscriptPath(urlContext + item.getManuscriptPath());
                            }
                        }
                    }
                    env.setVariable(ARTICLE_LIST, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(articleList));
                    redisTemplate.boundValueOps("directive_" + siteId + CMS_COLUMN_ARTICLE + "_" + columnIds + "_" + count + "_" + locationLevel + "_" + showImg + "_articleList").set(articleList);
                }

                env.setVariable(COLUMN_ARTICLE_LIST, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(columnList));
                redisTemplate.boundValueOps("directive_" + siteId + CMS_COLUMN_ARTICLE + "_" + columnIds + "_" + count + "_" + locationLevel + "_" + showImg + "_columnList").set(columnList);
            }
            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();
                    maps.put(CMS_COLUMN_ARTICLE, "");
                    maps.put(SITE_ID, String.valueOf(super.getLong(SITE_ID, params)));
                    maps.put(COLUMN_IDS, String.valueOf(super.getString(COLUMN_IDS, params)));
                    maps.put(COLUMN_ID, String.valueOf(super.getLong(COLUMN_ID, params)));
                    maps.put(SORT, String.valueOf(super.getString(SORT, params)));
                    maps.put(IS_STICK_COUNT, String.valueOf(super.getInt(IS_STICK_COUNT, params)));
                    maps.put(COUNT, String.valueOf(super.getInt(COUNT, params)));
                    maps.put(LOCATION_LEVEL, String.valueOf(super.getInt(LOCATION_LEVEL, params)));
                    maps.put(SHOW_IMG, String.valueOf(super.getInt(SHOW_IMG, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                throw new RuntimeException("分类所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
